package com.gaohe.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gaohe.common.R;
import com.gaohe.mapper.ClassesMapper;
import com.gaohe.mapper.UserCardMapper;
import com.gaohe.mapper.UserClassMapper;
import com.gaohe.pojo.Classes;
import com.gaohe.pojo.User;
import com.gaohe.pojo.UserCard;
import com.gaohe.pojo.UserClass;
import com.gaohe.service.UserClassService;
import com.gaohe.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/userClasses")
public class UserClassController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserClassMapper userClassMapper;
    @Autowired
    private ClassesMapper classesMapper;
    @Autowired
    private UserCardMapper userCardMapper;
    //会员选课业务
    @PostMapping("/chooseClasses")
    public R chooseClasses(@RequestBody Map<String,Long> map){
        log.info("会员选课业务：{}",map);
        //1.接收用户ID 课程Id
        Long userId=map.get("userId");
        Long classId=map.get("classId");


        //2.查询课程信息
        Classes classes = classesMapper.selectById(classId);
        //课程过期
        if(!classes.getEndTime().isAfter(LocalDateTime.now())){
            return R.error("课程过期");
        }
        //课程人数已满
        if(classes.getPnum()>=classes.getPmax()){
            return R.error("课程人数已满");
        }



        //3.获取用户的卡信息
        LambdaQueryWrapper<UserCard> qw = new LambdaQueryWrapper<>();
        qw.eq(UserCard::getUserId,userId);
        List<UserCard> userCards = userCardMapper.selectList(qw);

        //4.卡是否过期
        //次数卡 次数用尽
        //禁用
        //卡和课tags标签有关联
        //可用不可用 描述字段（数据库没有 业务会用）
        List<UserCard> userCardOk = userCards.stream().filter(item -> {
            //1.过期
            return item.getEndDate().isAfter(LocalDateTime.now());
        }).filter(item -> {
            //2.次数卡 次数用尽
            boolean flag = false;
            if (item.getType().equals("期限卡")) {
                flag = true;
            }
            if (item.getType().equals("次卡") && item.getCount() >= 1) {
                flag = true;
            }
            return flag;
        }).filter(item -> {
            String _tagsCard = item.getTags();
            String[] tagsCard = _tagsCard.split(",");
            String _tagsClass = classes.getTags();
            String[] tagsClass = _tagsClass.split(",");
            //获取两个集合的交集部分
            Collection<String> intersection = CollectionUtil.intersection
                    (Arrays.asList(tagsCard), Arrays.asList(tagsClass));
            return intersection != null && intersection.size() > 0 ? true : false;
        }).map(item -> {
            //处理业务 并返回对象 用作收集
            //对可用卡做一个标识
            item.setDisabled(true);
            return item;
        }).toList();

        //5.可用卡集合  null "" []
        if(StringUtils.isEmpty(userCardOk)||userCardOk.size()<=0){
            return R.error("没有可以使用的卡片");
        }

        //6.客户去选择卡
        //自动业务-自动帮用户去选择
        //定义用户使用的卡
        UserCard thisUserCard=null;
        //是否有期限卡-立即使用
        for(UserCard userCard:userCardOk){
            if(userCard.getType().equals("期限卡")){
                thisUserCard=userCard;
                break;
            }
        }
        //没有期限卡 是否有次卡-修改此卡次数 使用
        if(thisUserCard==null){
            for(UserCard userCard:userCardOk){
                if(userCard.getType().equals("次卡")){
                    userCard.setCount(userCard.getCount()-1);
                    //卡片信息同步
                    userCardMapper.updateById(userCard);
                    thisUserCard=userCard;
                    break;
                }
            }

        }


        //7.查询用户信息
        User user = userService.getById(userId);


        //7.在用户-课程userClass中间表新增数据
        UserClass userClass = new UserClass();
        userClass.setUserId(userId);
        userClass.setClassId(classId);
        userClass.setUserName(user.getName());

        userClass.setStatus(1);
        userClass.setCreateTime(LocalDateTime.now());
        userClass.setTags(classes.getTags());

        userClassMapper.insert(userClass);

        return R.success("选课成功");
    }
    @GetMapping("/{id}")
    public R findById(@PathVariable Long id){
        UserClass userClass = userClassMapper.selectById(id);
        return R.success(userClass);
    }
    @Autowired
    private UserClassService userClassService;
    @GetMapping("/getClassesTotalCount/{id}")
    public R getClassesTotalCount(@PathVariable Long id){
      long total=userClassService.getClassesTotalCount(id);
      return R.success(total);

    }
    @GetMapping("/getMouthTotal/{id}")
    public R getMouthTotal(@PathVariable Long id){
       long total= userClassService.getMouthTotal(id);
       return R.success(total);
    }
    @GetMapping("/getClassesByUserId/{id}")
    public R getClassesByUserId(@PathVariable Long id){
        LambdaQueryWrapper<UserClass> qw = new LambdaQueryWrapper<>();
        qw.eq(UserClass::getClassId,id);
        List<UserClass> list = userClassService.list(qw);
        ArrayList<Long> ids = new ArrayList<>();
        for (UserClass userClass : list) {
            ids.add(userClass.getUserId());
        }
        LambdaQueryWrapper<User> qw1 = new LambdaQueryWrapper<>();
        qw1.in(!StringUtils.isEmpty(ids),User::getId,ids);
        qw1.select(User::getName,User::getPhone);
        List<User> list1 = userService.list(qw1);
        return R.success(list1);
    }
      @PutMapping("/attendance")
      public R updateStatus(@RequestParam Long classId,
                            @RequestParam Long userId,@RequestParam int status){
          LambdaQueryWrapper<UserClass> qw = new LambdaQueryWrapper<>();
          qw.eq(UserClass::getClassId,classId);
          qw.eq(UserClass::getUserId,userId);
          userClassService.remove(qw);
          UserClass user = userClassService.getOne(qw);
          user.setStatus(status);
          boolean b = userClassService.save(user);
          return b?R.success("修改成功"):R.error("修改失败");
      }



}
